package com.springboot.common.convert;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;

/**
 * @Author: TongRui乀
 * @Date: 2020-05-23 17:05
 * @description：  请求和响应信息的序列化和反序列化
 */
public class PropertiesHttpMessageConverter implements HttpMessageConverter<Properties> {

    /**
     *  判单当前处理类是否可以处理读操作  也就是入参处理
     * @param aClass
     * @param mediaType
     * @return
     */
    @Override
    public boolean canRead(Class<?> aClass, MediaType mediaType) {
        return aClass.equals(Properties.class);
    }

    /**
     *  判断当前处理类是否可以处理写操作  也就是响应处理
     * @param aClass
     * @param mediaType
     * @return
     */
    @Override
    public boolean canWrite(Class<?> aClass, MediaType mediaType) {
        return aClass.equals(Properties.class);
    }

    /**
     *  获取支持的内容类型 也就是Context-Type  {@link MediaType}
     * @return
     */
    @Override
    public List<MediaType> getSupportedMediaTypes() {
        return Arrays.asList(new MediaType("text", "properties"));
    }

    /**
     *  入参处理
     * @param aClass
     * @param httpInputMessage
     * @return
     * @throws IOException
     * @throws HttpMessageNotReadableException
     */
    @Override
    public Properties read(Class<? extends Properties> aClass, HttpInputMessage httpInputMessage) throws IOException, HttpMessageNotReadableException {

        InputStream body = httpInputMessage.getBody();

        Properties properties = new Properties();

        properties.load(body);

        return properties;
    }

    /**
     *  响应处理
     * @param properties
     * @param mediaType
     * @param httpOutputMessage
     * @throws IOException
     * @throws HttpMessageNotWritableException
     */
    @Override
    public void write(Properties properties, MediaType mediaType, HttpOutputMessage httpOutputMessage) throws IOException, HttpMessageNotWritableException {

        properties.store(httpOutputMessage.getBody(), "自定义的序列化方式");

    }
}
